package fun.eliauk.treedemo.utils.encrypt;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@ConditionalOnProperty(value = "qqzj.encrypt", havingValue = "aes",matchIfMissing = true)
@Service
@Slf4j
public class AESEncryptService implements EncryptService{

    @Value("${qqzj.aes-key}")
    private String KEY;

    @Override
    public String encrypt(String content) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), Constants.AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, Constants.AES);
            Cipher cipher = Cipher.getInstance(Constants.AES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] valueByte = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(valueByte);
        } catch (Exception e) {
            log.error("加密失败：", e);
            throw new RuntimeException("encrypt fail!", e);
        }
    }

    @Override
    public String decrypt(String content) {
        try {
            byte[] originalData = Base64.getDecoder().decode(content);
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), Constants.AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, Constants.AES);
            Cipher cipher = Cipher.getInstance(Constants.AES);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] valueByte = cipher.doFinal(originalData);
            return new String(valueByte, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("解密失败：", e);
            throw new RuntimeException("decrypt fail!", e);
        }
    }

}